<template>
  <div class="app-container">
    <form-filter :loading="loading" @submit-form="submitFilterForm"/>
    <div style="padding: 10px 0;">
      <el-button-group>
        <el-button
          v-if="roleCheck('batch-lock')"
          type="danger"
          size="mini"
          @click="toggleMultipAcountLock(ids,1)"
        >批量锁定</el-button>
        <el-button
          v-if="roleCheck('batch-lock')"
          type="warning"
          size="mini"
          @click="toggleMultipAcountLock(ids,2)"
        >批量解锁</el-button>
        <el-button
          v-if="roleCheck('batch-modify-level')"
          type="danger"
          size="mini"
          @click="toggleMemberLevel(ids,1)"
        >批量修改层级</el-button>
        <el-button
          v-if="roleCheck('batch-update-vip')"
          type="warning"
          size="mini"
          @click="toggleVipLevel(ids,0)"
        >批量修改VIP</el-button>
         <el-button
          v-if="roleCheck('batch-unlock-vip')"
          type="danger"
          size="mini"
          @click="toggleVipLevel(ids,1)"
        >批量解锁VIP</el-button>
        <el-button type="primary" size="mini" icon="el-icon-download" @click="exportHandle">导出</el-button>
      </el-button-group>
    </div>
    <el-table
      class="el-table-align-center"
      :data="tableData.list"
      border
      ref="multipleTable"
      v-loading="loading"
      element-loading-text="加载中..."
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" ></el-table-column>

      <el-table-column label="账号名" width="150" fixed>
        <template slot-scope="{row}">
          <div v-if="roleCheck('detail-btn')" class="undeline-link" @click="showMember(row)">
            <svg-icon v-if="[1,2].indexOf(row.status)>-1" :icon-class="'lock'" style="color: red;"></svg-icon>
            <span class="online-tag online" v-else-if="row.online">在线</span>
            <span class="online-tag offline" v-else>离线</span>
            <span class="clipboard-btn" :data-clipboard-text="row.username">{{row.username}}</span>
          </div>
          <div v-else-if="roleCheck({exclude:'detail-btn'})">
            <svg-icon v-if="[1,2].indexOf(row.status)>-1" :icon-class="'lock'" style="color: red;"></svg-icon>
            <span class="online-tag online" v-else-if="row.online">在线</span>
            <span class="online-tag offline" v-else>离线</span>
            <span class="clipboard-btn" :data-clipboard-text="row.username">{{row.username}}</span>
          </div>
          <!--<div class="special-label">专享</div>-->
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="150" prop="reallyName">
        <!-- <template slot-scope="{row}">
         {{row.username.subtring(0, 1)}} *{{row.name.subtring(row.username.length-2, row.username.length-1)}}
        </template>-->
      </el-table-column>
      <el-table-column label="上级代理" width="150" prop="parentName">
        <template slot-scope="scope">
          <el-button
            v-if="roleCheck('agency')"
            size="mini"
            type="warning"
            plain
            @click="handleChangeProxy(scope.$index,scope.row)"
          >{{scope.row.parentName}}</el-button>
          <el-button
            v-else-if="roleCheck({exclude: 'agency'})"
            size="mini"
            type="warning"
            plain
          >{{scope.row.parentName}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="玩家层级" width="150" prop="levelName"/>
      <el-table-column label="层级状态" width="120" prop="levelStatus">
        <template slot-scope="{row}">
          <el-tag v-if="row.levelStatus === 1" type="warning">已锁定</el-tag>
          <el-tag v-else type="success">未锁定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="VIP等级" width="150" prop="vipLevel">
        <template slot-scope="{row}">
          {{row.vipLevel | VIPlevel}}
        </template>
      </el-table-column>
      <el-table-column label="VIP状态" width="150" prop="lockStatus">
        <template slot-scope="{row}">
           {{row.lockStatus==0?'未锁定':'已锁定'}}
        </template>
      </el-table-column>
      <el-table-column label="主账户余额" width="150" prop="balance">
        <template slot-scope="{row}">{{ row.balance | currency}}</template>
      </el-table-column>
      <el-table-column label="剩余取款流水" width="150" prop="money_stream">
        <template slot-scope="{row}">
          <div class="rest-withdraw-water" @click="showRunWaterInfo(row)">
            {{ (row.freezeBalance - row.validBalance < 0 ? 0 : row.freezeBalance - row.validBalance) | currency('',2,{type:2}) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" width="180" prop="registerDate">
        <template slot-scope="{row}">{{ row.registerDate | toTime}}</template>
      </el-table-column>
      <!--<el-table-column label="注册IP" width="150" prop="register_ip">-->
      <!--<template slot-scope="{row}">{{ row.register_ip}}</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column label="本次登录时间" width="150" prop="login_time">-->
      <!--<template slot-scope="{row}">{{ row.login_time | toTime}}</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column label="本次登录IP" width="150" prop="login_ip" />-->
      <el-table-column label="备注" width="150" prop="remark" fixed="right">
        <template slot-scope="{row,$index}">
          <el-tooltip effect="dark" :content="row.remark" placement="top" v-if="row.remark">
            <div
              class="undeline-link text-nowrap"
              @click="handleChangeComment($index,row)"
            >{{row.remark}}</div>
          </el-tooltip>
          <div
            v-else-if="roleCheck('backup')"
            class="undeline-link"
            @click="handleChangeComment($index,row)"
          >{{'添加备注'}}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120" prop="status">
        <template slot-scope="{row,$index}">
          <el-tag v-if="row.status === 1 " type="danger">完全锁定</el-tag>
          <el-tag v-else-if="row.status === 2" type="warning">间接锁定</el-tag>
          <el-tag v-else-if="row.status === 3 " type="info">审核中</el-tag>
          <el-tag v-else-if="row.status === 4 " type="info">登录锁定</el-tag>
          <template v-else-if="row.status === 6 ">
            <el-tag type="warning">间接锁定</el-tag>
            <el-tag type="info">登录锁定</el-tag>
          </template>
          <el-tag v-else type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template slot-scope="{row,$index}">
          <el-button v-if="roleCheck('edit-btn')" type="text" @click="handleEdit($index, row)">编辑资料</el-button>
          <el-button
            v-if="roleCheck('lock') && [1,2,4].indexOf(row.status) !== -1"
            type="text"
            @click="toggleAcountLock(row,4)"
          >解锁</el-button>
          <el-button v-else-if="roleCheck('lock')" type="text" @click="toggleAcountLock(row,3)">锁定</el-button>
          <el-button type="text" v-if="roleCheck('modify-level')" @click="toggleMemberLevel(row,2)">修改层级</el-button>
          <el-button type="text" v-if="roleCheck('sync-member-user')" @click="syncData(row)">同步</el-button>
          <el-button type="text"  @click="changeVipLevel(row,1)" v-if="roleCheck('update-vip')">修改VIP</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="gridSizeChange"
        @current-change="gridCurrentChange"
        :current-page="filters.page"
        :page-sizes="gridPageSize"
        :page-size="filters.size"
        :layout="gridLayout"
        :total="tableData.total"
      ></el-pagination>
    </div>

    <agency-dialog
      :dialogVisible="proxyDialogVisible"
      v-if="proxyDialogVisible"
      :row-data="rowData"
      @cancel="proxyDialogVisible = false"
    />
    <comment-dialog
      v-if="commentDialogVisible"
      v-model="commentDialogVisible"
      :row-data="rowData"
      @cancel="commentDialogVisible = false"
      @submit="commentChangeNow"
    />
    <account-lock-dialog
      v-model="accounLockVisible"
      v-if="accounLockVisible"
      :lock-class="lockClass"
      :status="ids[0].status"
      @cancel="accounLockVisible=false"
      @submit="accountLockSubmit"
    />
    <member-level-dialog
      v-model="memberLevelVisible"
      :idList='levelList'
      :type='levelType'
      @cancel="memberLevelVisible = false"
      @submit="submitFinished"
    />
    <vip-level-dialog
      :vipType="vipType"
      :dialogVisible="vipLevelVisible"
      v-if="vipLevelVisible"
      :rows='ids'
      :type='levelType'
      @cancel="vipLevelVisible = false"
      @getTableType="getTableType"
    />
    <vip-level-table
      :vipTableType="vipTableType"
      :dialogVisible="vipTableVisible"
      v-if="vipTableVisible"
      :rows='rows'
      :type='levelType'
      @cancel="vipTableVisible = false"


    />
    <custom-dialog :visible="memberDetailVisible" :title="memberTitle" :callback="hideMemberDetail">
      <transition name="fade-transform" mode="out-in">
        <member-detail v-if="memberDetailVisible" :member="member"></member-detail>
      </transition>
    </custom-dialog>
    <custom-dialog :visible="editCardDialog" :title="editTitle" :callback="hideEdit">
      <transition name="fade-transform" mode="out-in">
        <edit-dialog v-if="editCardDialog" :edit-data="editData"></edit-dialog>
      </transition>
    </custom-dialog>

    <apply-dialog/>

    <el-dialog :title="'提现流水详情：'+runningWaterRow.username" :visible.sync="runningWaterShowFlag" width="85%" append-to-body class="running-water-detail-dialog">
      <running-water-info v-if="runningWaterShowFlag" :runningWaterRow="runningWaterRow"/>
    </el-dialog>
  </div>
</template>
<script>
import formFilter from './formFilter';
import editDialog from './editDialog';
import AgencyDialog from '@/views/agency/list/agencyDialog';
import commentDialog from './commentDialog';
import applyDialog from './applyDialog';
import accountLockDialog from './accountLockDialog';
import CustomDialog from '@/components/customDialog/index';
import memberDetail from '../detail/index';
import runningWaterInfo from '@/views/member/detail/runningWaterInfo';
import VipLevelDialog from './vipLevelDialog';
import VipLevelTable from './vipLevelTable';
import {
  getMemberList, setMembersStatus, exportMembershipList, memberSyncData,
} from '@/services/api/member';
import memberLevelDialog from './memberLevelDialog';
import { grid, dialog } from '@/build';

export default {
  name: 'member-list',
  components: {
    CustomDialog,
    formFilter,
    editDialog,
    commentDialog,
    applyDialog,
    accountLockDialog,
    memberDetail,
    AgencyDialog,
    runningWaterInfo,
    memberLevelDialog,
    VipLevelDialog, // vip第一步弹框
    VipLevelTable, // vip第二步弹框
  },
  mixins: [grid, dialog],
  data() {
    return {
      row: {},
      userId: null,
      total: null,
      filters: {
        size: 20,
        page: 1,
        online: -1,
        startDate: moment(consts.ONLINE_DATE).format('YYYY-MM-DD 00:00:00'),
        endDate: moment().format('YYYY-MM-DD 23:59:59'),
        lockStatus: '',
      },
      tableData: {},
      editCardDialog: false,
      editData: {},
      commentDialogVisible: false,
      proxyDialogVisible: false,
      accounLockVisible: false,
      memberDetailVisible: false,
      memberLevelVisible: false,
      vipLevelVisible: false,
      vipTableVisible: false,
      member: {},
      rowData: {},
      listLoading: true,
      memberTitle: '',
      editTitle: '',
      multipleSelection: [],
      ids: [],
      lockClass: 0,
      searchLoading: false,
      filterDateType: false,
      runningWaterShowFlag: false,
      levelType: 1,
      levelList: [],
      username: '',
      runningWaterRow: {},
      lockForm: {},
      vipType: 0, // 0修改等级，1解锁
      vipTableType: 0, // 0,批量，1，单个
      rows: [], // 选择的vip数据
    };
  },
  // created() {
  //   this.getList()
  // },
  computed: {
    // 计算表格左侧选中的用户的ID
    idsArr() {
      return this.ids.map(item => item.id);
    },
  },
  filters: {
    VIPlevel(value) {
      return _.find(vipManage.VIP_LEVEL, { value }).title;
    },
  },

  methods: {
    showRunWaterInfo(row) {
      this.runningWaterRow = row;
      this.runningWaterShowFlag = true;
    },

    handleEdit(index, row) {
      if (this.checkOper(row)) {
        return;
      }
      this.editCardDialog = true;
      window.scrollTo(0, 0);
      this.editTitle = `玩家账号:${row.username}`;
      this.editData = row;
      this.$store.commit(types.SET_MEMBER_ID, row.id);
    },
    hideEdit() {
      this.editCardDialog = false;
      this.$store.commit(types.SET_MEMBER_ID, 0);
    },
    defaultSelect(row, index) { // 先注释，duke确认lockStatus是vip功能才出现的字段
      // if (row.lockStatus === 1) {
      //   return false;
      // }
      // return true;
    },
    // 显示更换代理的Modal
    handleChangeProxy(index, row) {
      this.proxyDialogVisible = true;
      this.rowData = row;
    },

    // 显示添加备注的Modal
    handleChangeComment(index, row) {
      this.commentDialogVisible = true;
      this.rowData = _.cloneDeep(row);
    },
    commentChangeNow(form) {
      this.commentDialogVisible = false;
    },

    submitFilterForm(formInline) {
      const { registerTime } = formInline;
      let startDate;
      let endDate;
      if (!_.isUndefined(registerTime) && _.isArray(registerTime)) {
        startDate = formInline.registerTime[0];
        endDate = formInline.registerTime[1];
        formInline = { ...formInline, startDate, endDate };
      } else {
        this.filters.startDate = undefined;
        this.filters.endDate = undefined;
      }
      this.filters = { ...this.filters, ...formInline };
      this.gridSearch();
    },

    formSubmit() {},

    // 显示用户详情Tabs
    showMember(member) {
      window.scrollTo(0, 0);
      this.memberTitle = `玩家账号：${member.username ? member.username : member.blackTitle}`;
      this.member = member;
      this.memberDetailVisible = true;
      this.$store.commit(types.SET_MEMBER_ID, member.id);
      this.$store.commit(types.SET_MEMBER_INFO, member);
      this.$store.commit(types.SET_AGENCY, false);
    },
    hideMemberDetail() {
      this.$store.commit(types.SET_MEMBER_ID, 0);
      this.member = {};
      this.memberDetailVisible = false;
    },

    // 表格前面的checkbox操作
    handleSelectionChange(val) {
      this.ids = val;
      this.rows = val;
    },

    /**
     * lock_class:
     * 1.批量锁定
     * 2.批量解锁
     * 3.锁定
     * 4.解锁
     */
    toggleMultipAcountLock(ids, lockClass) {
      if (ids.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选中需要处理的数据',
        });
        return;
      }
      this.ids = ids;
      this.lockClass = lockClass;
      this.accounLockVisible = true;
    },
    toggleAcountLock(row, lockClass) {
      if (this.checkOper(row)) {
        return;
      }
      this.$refs.multipleTable.clearSelection();
      this.lockClass = lockClass;
      this.ids = [row];
      this.accounLockVisible = true;
    },


    // type 1 批量操作2，单个用户操作
    toggleMemberLevel(ids, type) {
      let levelList = [];
      if (type === 1) {
        levelList = ids;
      } else {
        levelList.push(ids);
      }
      if (levelList.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选中需要处理的数据',
        });
        return;
      }
      this.levelList = levelList;
      this.levelType = type;
      this.memberLevelVisible = true;
    },
    toggleVipLevel(ids, type) { // vip批量修改层级,解锁
      // type 0 修改vip 1解锁vip
      this.vipType = type;
      if (this.ids.length == 0) {
        this.$message({
          type: 'warning',
          message: '请选中需要处理的数据',
        });
        return;
      }

      this.vipLevelVisible = true;
    },
    getTableType(val) {
      this.vipTableType = val.tableType;
      this.rows = val.rows;
      this.vipTableVisible = true;
    },
    changeVipLevel(row, tableType) { // vip单个修改
      // tableType 0批量 1单个
      this.$refs.multipleTable.clearSelection();
      this.rows = [];
      this.rows.push(row);
      this.vipTableType = tableType;
      this.vipTableVisible = true;
    },
    checkOper(row) {
      //luckStatus不作为有无待审核操作判断（Vip锁定层级用），新增字段为unauditedLockStatus，0：没有，1：有
      if (row.unauditedLockStatus === 1) {
        this.$message({
          type: 'warning',
          message: '该用户已有未审核的操作',
        });
        return true;
      }
      return false;
    },
    accountLockSubmit(lockForm) {
      if (lockForm.type.includes(7)) {
        lockForm.type = 7;
      } else {
        lockForm.type = lockForm.type.join(',');
      }
      lockForm.ids = this.idsArr;
      lockForm.lockClass = this.lockClass;
      this.lockForm = { ...lockForm };
      this.doSave({ action: 'saveLock' });
    },

    memberLevelSubmit() {
      this.doGet({ action: 'getGrid' });
    },
    exportHandle() {
      const {
        status,
        levelId,
        searchType,
        keywords,
        online,
        minBalance,
        maxBalance,
        startDate,
        endDate,
        userType,
        page,
        size,
      } = this.filters;
      const ajaxData = {
        status,
        levelId,
        searchType,
        keywords,
        online,
        minBalance,
        maxBalance,
        startDate,
        endDate,
        userType,
        page,
        size,
      };
      const filename = '会员列表明细报表.csv';
      const header = [
        '账号名',
        '姓名',
        '上级代理',
        '玩家层级',
        '层级状态',
        '主账户余额',
        '剩余取款流水',
        '注册时间',
        '状态',
        '备注',
      ];
      const filterField = [
        'username',
        'reallyName',
        'parentName',
        'levelName',
        'levelStatus',
        'balance',
        'leftAmount',
        'registerDate',
        'status',
        'remark',
      ];
      exportMembershipList(ajaxData).then(([result, data]) => {
        if (result) {
          const exportData = this.responseFormatter(data.list);
          this.export2Excel(header, filterField, exportData, filename);
        } else {
          this.$message({ message: `导出失败,${data.message}`, type: 'warning' });
        }
      });
    },
    responseFormatter(data) {
      data.map((item) => {
        item.registerDate = _.toTime(item.registerDate);
        item.balance = _.currency(item.balance);
        // item.leftAmount = item.leftAmount;
        const amount = item.freezeBalance - item.validBalance < 0 ? 0 : item.freezeBalance - item.validBalance;
        item.leftAmount = _.currency(amount,'', 2, {type:2});
        item.status = _.toConverter(item.status, 'EXPORT_MEMBER_STATUS');
        item.levelStatus = _.toConverter(item.levelStatus, 'LEVEL_STATUS');
      });
      return data;
    },
    syncData(row) {
      this.username = row.username;
      this.doSave({ action: 'syncUserData' });
    },
  },
  mounted() {
    this.bindGet(getMemberList, 'tableData', {
      sendingData: 'filters',
      action: 'getGrid',
      format: (data) => {
        data.list.forEach((item) => {
          item.remark = item.remark.replace(/\s+/g, '');
        });
        return data;
      },
    });
    this.getAll();
    this.bindSave(memberSyncData, 'syncUserData', 'username', {
      successMessage: '同步成功',
      beforeSend: data => ({ username: data }),
      afterSuccess: ([result]) => {
        if (result) {
          this.doGet({ action: 'getGrid' });
        }
      },
    });
    this.bindSave(setMembersStatus, 'saveLock', 'lockForm', {
      afterSuccess: ([result, data]) => {
        this.accounLockVisible = false;
        if (result) {
          if (data.failNum > 0 && [3, 4].indexOf(this.lockClass) != -1) {
            this.$message({
              type: 'success',
              message: `${this.lockClass == 3 ? '锁定' : '解锁'}失败,失败原因：${data.failMessage}`,
            });
          }
          if (data.failNum > 0 && data.successNum < 1 && [3, 4].indexOf(this.lockClass) == -1) {
            this.$message({
              type: 'success',
              message: `失败批量${this.lockClass == 1 ? '锁定' : '解锁'}${data.failNum}个操作,失败原因：${data.failMessage}`,
            });
          } else if (data.failNum > 0 && data.successNum > 0 && [3, 4].indexOf(this.lockClass) == -1) {
            this.$message({
              type: 'success',
              message: `成功批量${this.lockClass == 1 ? '锁定' : '解锁'}${data.successNum}个操作，失败批量${this.lockClass == 1 ? '锁定' : '解锁'}${data.failNum}个操作,失败原因：${data.failMessage}`,
            });
          } else if (data.failNum < 1 && data.successNum > 0 && [3, 4].indexOf(this.lockClass) == -1) {
            this.$message({
              type: 'success',
              message: `成功批量${this.lockClass == 1 ? '锁定' : '解锁'}${data.successNum}个操作`,
            });
          }
          this.gridSearch();
        }
      },
    });


    const { member } = this.$route.params;
    if (member) {
      const { usernameRisk } = member || member.blackTitle;
      const obj = {
        ...member,
        username: usernameRisk,
        id: member.userId,
      };
      this.showMember(obj);
    }

  },
};
</script>
<style lang="scss">
.el-table-align-center {
  &.el-table {
    width: 100%;
    text-align: center !important;

    th {
      text-align: center !important;
    }
  }
}

.undeline-link {
  display: block;
  text-align: center;
  text-decoration: underline;
  cursor: pointer;
}

.special-label {
  position: absolute;
  right: 0;
  top: 0;
  background-color: purple;
  color: #fff;
  padding: 0 5px;
  border-radius: 5px;
  font-size: 12px;
  transform: scale(0.8);
  border-radius: 5px;
  transform-origin: top right;
}

.online-tag {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  text-indent: -9999px;
  text-align: center;
  overflow: hidden;
  vertical-align: middle;
  position: relative;

  &.offline {
    background: #f5f5f5;
    border: 1px solid #ccc;
  }

  &.online {
    background: #5ce45c;

    &:after {
      content: "";
      position: absolute;
      left: 50%;
      top: 50%;
      margin: -2px 0 0 -2px;
      display: inline-block;
      width: 4px;
      height: 4px;
      border-radius: 50%;
      background: #f1fff2;
      transform-origin: center;
      animation: scaleX 1.2s ease-in-out infinite;
    }
  }
}

@keyframes scaleX {
  0% {
    transform: scale(1.2);
  }
   36% {
    transform: scale(0.8);
  }
  100% {
    transform: scale(1);
  }
}
  .running-water-detail-dialog{
    padding-left: 10%;
  }
  .rest-withdraw-water{
    display: block;
    text-align: center;
    text-decoration: underline;
    cursor: pointer;
  }
</style>
